package com.chukun.multi.pipeline.reusable;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public abstract class AbstractPipe<IN,OUT> implements Pipe<IN,OUT> {

    protected volatile Pipe<IN,OUT> nextPipe = null;
    protected volatile PipeContext pipeCtx;

    @Override
    public void init(PipeContext pipeCtx) {
        this.pipeCtx = pipeCtx;
    }

    @Override
    public void setNextPipe(Pipe<IN,OUT> nextPipe) {
        this.nextPipe = nextPipe;
    }

    @Override
    public void shutdown(long timeout, TimeUnit unit) {
        // 什么也不做
    }

    /**
     * 留给子类实现。用于子类实现任务的处理逻辑
     * @param input
     * @return
     * @throws InterruptedException
     */
    protected abstract OUT doProcess(IN input) throws InterruptedException, PipeException;

    @Override
    public void process(IN input) throws InterruptedException {
        try{
            OUT out = doProcess(input);
            if (!Objects.isNull(nextPipe)) {
                if (!Objects.isNull(out)) {
                    ((Pipe<OUT,?>) nextPipe).process(out);
                }
            }
        }catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }catch (PipeException e) {
            pipeCtx.handleError(e);
        }
    }
}
